package com.opticon.vaadinR.core.conf;

import com.opticon.vaadinR.exceptions.RCallerException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

import java.io.File;

/**
 * Date: 10/02/11
 * Time: 11:09
 */
public class RCallerConfiguration {
    private static Logger logger = Logger.getLogger(RCallerConfiguration.class);

    private static PropertiesConfiguration config;
    private static File iWorkSpace = null;

    public static final String LOCATION_MAC = "mac.location.rscript";
    public static final String LOCATION_WINDOWS = "win.location.rscript";
    public static final String LOCATION_LINUX = "linux.location.rscript";


    public static String getRscriptLocation() {

        String OS = System.getProperty("os.name");
        if (OS.startsWith("Windows")) {
            return config.getString(LOCATION_WINDOWS);

        } else if (OS.startsWith("Mac")) {
            return config.getString(LOCATION_MAC);

        } else if (OS.startsWith("Linux")) {
            return config.getString(LOCATION_LINUX);
        } else {
            try {
                throw new RCallerException("There is no RScript location defined for this operating system ('OS')");
            } catch (RCallerException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public static String setRscriptLocation(String aRscriptLocation){

        String OS = System.getProperty("os.name");
        if (OS.startsWith("Windows")) {
            config.setProperty(LOCATION_WINDOWS, aRscriptLocation);

        } else if (OS.startsWith("Mac")) {
            config.setProperty(LOCATION_MAC, aRscriptLocation);

        } else if (OS.startsWith("Linux")) {
            config.setProperty(LOCATION_LINUX, aRscriptLocation);

        } else {
            try {
                throw new RCallerException("There is no RScript location defined for this operating system ('OS')");
            } catch (RCallerException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return null;
    }


    static {
        try {
            config = new PropertiesConfiguration("config/rcaller.properties");
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println(getRscriptLocation());
        setRscriptLocation("test_new_locations");
        System.out.println(getRscriptLocation());
    }
}
